# from Task.tasks import add2
from django_celery_beat import models as task_models
from django_celery_results.models import TaskResult  # 执行结果
from Task import serializers
from Task import models
from utils.get_query_params import GetQueryParams
from utils.commonviews import CommonAPIView
from rest_framework.response import Response
from utils.base_response import BaseResponse
from rest_framework.views import APIView
from django.conf import settings
from utils.shell_tool import exe_shell
import os

from ProjectTool.AutomatedTool import automated_tool


class PeriodicTaskModelViewSet(CommonAPIView):
    query_set = task_models.PeriodicTask.objects.all().order_by('id')
    serializer_class = serializers.PeriodicTaskSerializer
    input_get_list = [('task_id', 'id'),
                      ('inputObjName', 'name__contains'),
                      ('interval_id', 'interval'),
                      ('crontab_schedule_id', 'crontab'),
                      ('solar_id', 'solar'),
                      ]
    input_put_list = [('task_id', 'id')]
    input_delete_list = [('task_id', 'id')]
    input_dict = GetQueryParams


class CrontabScheduleModelViewSet(CommonAPIView):
    query_set = task_models.CrontabSchedule.objects.all().order_by('id')
    serializer_class = serializers.CrontabScheduleSerializer
    input_get_list = [('crontab_schedule_id', 'id')]
    input_put_list = [('crontab_schedule_id', 'id')]
    input_delete_list = [('crontab_schedule_id', 'id')]
    input_dict = GetQueryParams

    def put(self, request):
        res = BaseResponse()
        input_put_list = self.get_input_put_list()
        input_dict = self.get_input_dict().get_query_params(request, input_put_list)
        if not input_dict:
            res.status = 1
            res.msg = '参数有误，更新失败！'
            return Response(res.dict)
        queryset = self.get_queryset().filter(**input_dict)
        if queryset.count():
            data = request.data
            serializer = self.get_serializer(queryset.first(), data=data, partial=True)
            if serializer.is_valid():
                queryset.update(**data)
                res.data = serializer.data
                res.msg = '更新成功'
            else:
                res.msg = '数据异常，本次更新失败！'
                res.error = serializer.errors
                res.status = 1
        else:
            res.msg = '没有对应数据,更新失败'
            res.status = 1
        return Response(res.dict)

    def post(self, request):
        res = BaseResponse()
        data = request.data
        serializer = self.get_serializer(data=data)
        if serializer.is_valid():
            serializer.save()
            res.data = serializer.data
            update_query = self.query_set.filter(id=res.data.get('id'))
            update_query.update(timezone=data.get('timezone'))
            res.msg = '创建成功'
        else:
            res.msg = '添加失败'
            res.error = serializer.errors
            res.status = 1
        return Response(res.dict)

    def delete(self, request):
        res = BaseResponse()
        input_delete_list = self.get_input_delete_list()
        input_dict = self.get_input_dict().get_query_params(request, input_delete_list)
        if not input_dict:
            res.status = 1
            res.msg = '删除失败，参数有误！'
            return Response(res.dict)
        queryset = self.get_queryset().filter(**input_dict)
        if queryset.count():
            try:
                task_count = queryset.first().periodictask_set.count()
                if task_count:
                    res.msg = '存在关联任务，请处理后再删除！'
                    res.status = 1
                else:
                    queryset.delete()
                    res.msg = '删除成功'
            except Exception as err:
                res.msg = '删除失败，请联系管理员'
                res.error = str(err.args)
                res.status = 1
        else:
            res.msg = '删除失败，没有对应数据'
            res.status = 1
        return Response(res.dict)


class IntervalScheduleModelViewSet(CommonAPIView):
    query_set = task_models.IntervalSchedule.objects.all().order_by('id')
    serializer_class = serializers.IntervalScheduleSerializer
    input_get_list = [('interval_id', 'id'), ('inputObjName', 'period__contains')]
    input_put_list = [('interval_id', 'id')]
    input_delete_list = [('interval_id', 'id')]
    input_dict = GetQueryParams

    def delete(self, request):
        res = BaseResponse()
        input_delete_list = self.get_input_delete_list()
        input_dict = self.get_input_dict().get_query_params(request, input_delete_list)
        if not input_dict:
            res.status = 1
            res.msg = '删除失败，参数有误！'
            return Response(res.dict)
        queryset = self.get_queryset().filter(**input_dict)
        if queryset.count():
            try:
                task_count = queryset.first().periodictask_set.count()
                if task_count:
                    res.msg = '存在关联任务，请处理后再删除！'
                    res.status = 1
                else:
                    queryset.delete()
                    res.msg = '删除成功'
            except Exception as err:
                res.msg = '删除失败，请联系管理员'
                res.error = str(err.args)
                res.status = 1
        else:
            res.msg = '删除失败，没有对应数据'
            res.status = 1
        return Response(res.dict)


class SolarScheduleModelViewSet(CommonAPIView):
    query_set = task_models.SolarSchedule.objects.all().order_by('id')
    serializer_class = serializers.SolarScheduleSerializer
    input_get_list = [('solar_id', 'id'), ('inputObjName', 'event__contains')]
    input_put_list = [('solar_id', 'id')]
    input_delete_list = [('solar_id', 'id')]
    input_dict = GetQueryParams

    def delete(self, request):
        res = BaseResponse()
        input_delete_list = self.get_input_delete_list()
        input_dict = self.get_input_dict().get_query_params(request, input_delete_list)
        if not input_dict:
            res.status = 1
            res.msg = '删除失败，参数有误！'
            return Response(res.dict)
        queryset = self.get_queryset().filter(**input_dict)
        if queryset.count():
            try:
                task_count = queryset.first().periodictask_set.count()
                if task_count:
                    res.msg = '存在关联任务，请处理后再删除！'
                    res.status = 1
                else:
                    queryset.delete()
                    res.msg = '删除成功'
            except Exception as err:
                res.msg = '删除失败，请联系管理员'
                res.error = str(err.args)
                res.status = 1
        else:
            res.msg = '删除失败，没有对应数据'
            res.status = 1
        return Response(res.dict)


class TaskResultModelViewSet(CommonAPIView):
    query_set = TaskResult.objects.all().order_by('-id')
    serializer_class = serializers.TaskResultSerializer
    input_get_list = [('task_result_id', 'id'), ('status', 'status')]
    input_put_list = [('task_result_id', 'id')]
    input_delete_list = [('task_result_id', 'id')]
    input_dict = GetQueryParams


class MyShellModelViewSet(CommonAPIView):
    query_set = models.MyShell.objects.all().order_by('id')
    serializer_class = serializers.MyShellSerializer
    input_get_list = [('shell_id', 'id')]
    input_put_list = [('shell_id', 'id')]
    input_delete_list = [('shell_id', 'id')]
    input_dict = GetQueryParams


# 执行shell
class ExeShell(APIView):
    def post(self, request):
        # 查询数据库中的数据
        shell_id = request.data.get('id')
        queryset = models.MyShell.objects.filter(id=shell_id).first()
        shell_str = queryset.shell
        path = settings.BASE_DIR
        encoding = queryset.encoding
        shell_status = queryset.shell_status
        file_status = queryset.file_status
        if file_status:
            path_name = os.path.join(settings.BASE_DIR, 'celerybeat.pid')
            if os.path.isfile(path_name):
                os.remove(path_name)
        data = exe_shell(shell_str, path, encoding, shell_status)
        return Response(data)


# def index(request):
#     res = add2.delay(1, 3)
#
#     return JsonResponse({"status": "success", "task_id": res.task_id})

class Test(APIView):
    def get(self, request):
        res = automated_tool.test_cases(id=request.GET.get('id'))
        return Response(res.dict)
